# -*- coding: iso-8859-2 -*-

import os

from authorshipanalyzer.file import Path
from authorshipanalyzer.utils import sortDictionaryByValue

class SVMExperiment:
    '''
    Tracking SVM experiment
    '''
    
    def __init__(self, kernel):
        '''
        @param firstCounter: number of times when autor was correctly identified
        @param similiarityProc: list of procentage similiarities of each experiment
        @param rankDict: <rank, counter>
        @param kernel
        '''
        self.firstCounter = 0
        self.similarityProc = []
        self.rankDict = {}
        self.kernel = kernel
        
    def _addResolvedResult(self, rank, similarity):
        '''
        Save resolved result
        '''
        self.similarityProc.append(similarity)
        if rank == 1:
            self.firstCounter += 1
            
        if self.rankDict.has_key(rank):
            self.rankDict[rank] += 1
        else:
            self.rankDict[rank] = 1
    
    def addResult(self, uAuthor, result):
        '''
        Resolve result from classifier output and save values
        '''
        sortedResult = sortDictionaryByValue(result)
        rank = 0
        similarity = 0.0
        if result.has_key(uAuthor):
            similarity = result[uAuthor]          
        
        for singleRes in sortedResult:
            rank += 1
            if singleRes[0] == uAuthor:
                break
            
        self._addResolvedResult(rank, similarity)
    
    def printSVM(self):
        '''
        Print result of SVM comparison
        '''        
        # print procentage similarity result
        output = os.path.join(Path.getResourceDir(), "svm", self.kernel + "_proc.dat")
        outputFile = file(output, "w")
        for similarity in self.similarityProc:
            outputFile.write("%s\n" % similarity)
        outputFile.flush()
        outputFile.close()
        
        # print rank results
        output = os.path.join(Path.getResourceDir(), "svm", self.kernel + "_rank.dat")
        outputFile = file(output, "w")       
        keys = self.rankDict.keys()
        keys.sort()
        for key in keys:
            outputFile.write("%s %s\n" % (key, self.rankDict[key]))
        outputFile.flush()
        outputFile.close()
        
        # print overall result
        output = os.path.join(Path.getResourceDir(), "svm", self.kernel + "_res.dat")
        outputFile = file(output, "w")
        outputFile.write("%3.2f %s\n" % (float(self.firstCounter) / float(len(self.similarityProc)) * 100.0, self.kernel) )
        outputFile.flush()
        outputFile.close()
        
        